<template>
  <div class="page-container">
    <div class="content-box">
      <h2>帖子管理</h2>
      
      <!-- 统计卡片 -->
      <el-row :gutter="20" class="mb-20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: #409EFF;">
              <i class="el-icon-document"></i>
            </div>
            <div class="stat-content">
              <div class="stat-title">总帖子数</div>
              <div class="stat-value">{{ statistics.totalPosts || 0 }}</div>
            </div>
          </div>
        </el-col>
        
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: #E6A23C;">
              <i class="el-icon-warning-outline"></i>
            </div>
            <div class="stat-content">
              <div class="stat-title">待审核</div>
              <div class="stat-value">{{ statistics.pendingAuditPosts || 0 }}</div>
            </div>
          </div>
        </el-col>
        
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: #67C23A;">
              <i class="el-icon-circle-check"></i>
            </div>
            <div class="stat-content">
              <div class="stat-title">已发布</div>
              <div class="stat-value">{{ statistics.publishedPosts || 0 }}</div>
            </div>
          </div>
        </el-col>
        
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: #F56C6C;">
              <i class="el-icon-warning"></i>
            </div>
            <div class="stat-content">
              <div class="stat-title">违规帖子</div>
              <div class="stat-value">{{ statistics.violationPosts || 0 }}</div>
            </div>
          </div>
        </el-col>
      </el-row>
      
      <!-- 搜索筛选 -->
      <el-form :model="queryForm" :inline="true" class="search-form">
        <el-form-item label="关键词">
          <el-input v-model="queryForm.keyword" placeholder="搜索标题和内容" clearable style="width: 200px"></el-input>
        </el-form-item>
        
        <el-form-item label="发布者">
          <el-input v-model="queryForm.authorName" placeholder="请输入发布者姓名" clearable style="width: 150px"></el-input>
        </el-form-item>
        
        <el-form-item label="帖子状态">
          <el-select v-model="queryForm.postStatus" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="草稿" :value="0"></el-option>
            <el-option label="待审核" :value="1"></el-option>
            <el-option label="已发布" :value="2"></el-option>
            <el-option label="已下架" :value="3"></el-option>
            <el-option label="已删除" :value="4"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="审核状态">
          <el-select v-model="queryForm.auditStatus" placeholder="请选择审核状态" clearable style="width: 120px">
            <el-option label="待审核" :value="0"></el-option>
            <el-option label="审核通过" :value="1"></el-option>
            <el-option label="审核拒绝" :value="2"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch" icon="el-icon-search">搜索</el-button>
          <el-button @click="handleReset" icon="el-icon-refresh">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 批量操作 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button 
            type="primary" 
            @click="batchAudit(1)" 
            :disabled="selectedPosts.length === 0"
            icon="el-icon-check">
            批量通过
          </el-button>
          <el-button 
            type="warning" 
            @click="batchAudit(2)" 
            :disabled="selectedPosts.length === 0"
            icon="el-icon-close">
            批量拒绝
          </el-button>
          <el-button 
            type="success" 
            @click="batchPublish" 
            :disabled="selectedPosts.length === 0"
            icon="el-icon-upload">
            批量发布
          </el-button>
          <el-button 
            type="danger" 
            @click="batchTakeDown" 
            :disabled="selectedPosts.length === 0"
            icon="el-icon-download">
            批量下架
          </el-button>
        </div>
        
        <div class="toolbar-right">
          <el-button type="text" @click="handleRefresh" icon="el-icon-refresh">刷新</el-button>
        </div>
      </div>
      
      <!-- 帖子列表 -->
      <el-table 
        :data="postList" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border>
        <el-table-column type="selection" width="55"></el-table-column>
        
        <el-table-column prop="title" label="标题" width="200">
          <template slot-scope="scope">
            <el-link type="primary" @click="viewPostDetail(scope.row)">{{ scope.row.title }}</el-link>
          </template>
        </el-table-column>
        
        <el-table-column prop="authorName" label="发布者" width="100">
          <template slot-scope="scope">
            <div>{{ scope.row.authorName }}</div>
            <el-tag size="mini" :type="getAuthorTypeColor(scope.row.authorType)">
              {{ getAuthorTypeText(scope.row.authorType) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="categoryName" label="分类" width="100"></el-table-column>
        
        <el-table-column label="内容预览" width="200" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ getContentSummary(scope.row.content) }}
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <div>
              <el-tag :type="getPostStatusType(scope.row.postStatus)">
                {{ getPostStatusText(scope.row.postStatus) }}
              </el-tag>
            </div>
            <div style="margin-top: 4px;">
              <el-tag size="mini" :type="getAuditStatusType(scope.row.auditStatus)">
                {{ getAuditStatusText(scope.row.auditStatus) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="统计数据" width="120">
          <template slot-scope="scope">
            <div>浏览: {{ scope.row.viewCount || 0 }}</div>
            <div>点赞: {{ scope.row.likeCount || 0 }}</div>
            <div>评论: {{ scope.row.commentCount || 0 }}</div>
          </template>
        </el-table-column>
        
        <el-table-column label="特殊标记" width="100">
          <template slot-scope="scope">
            <div>
              <el-tag v-if="scope.row.isTop" size="mini" type="warning">置顶</el-tag>
              <el-tag v-if="scope.row.isEssence" size="mini" type="success">精华</el-tag>
              <el-tag v-if="scope.row.isRecommend" size="mini" type="primary">推荐</el-tag>
              <el-tag v-if="scope.row.isHot" size="mini" type="danger">热门</el-tag>
            </div>
            <div v-if="scope.row.violationType" style="margin-top: 4px;">
              <el-tag size="mini" type="danger">{{ getViolationTypeText(scope.row.violationType) }}</el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="创建时间" width="150">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button 
              v-if="scope.row.auditStatus === 0" 
              type="primary" 
              size="mini" 
              @click="auditPost(scope.row, 1)">
              通过
            </el-button>
            
            <el-button 
              v-if="scope.row.auditStatus === 0" 
              type="warning" 
              size="mini" 
              @click="auditPost(scope.row, 2)">
              拒绝
            </el-button>
            
            <el-button 
              v-if="scope.row.postStatus === 2" 
              type="danger" 
              size="mini" 
              @click="takeDownPost(scope.row)">
              下架
            </el-button>
            
            <el-dropdown @command="handleCommand" trigger="click">
              <el-button type="text" size="mini">
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="{action: 'view', row: scope.row}">查看详情</el-dropdown-item>
                <el-dropdown-item :command="{action: 'edit', row: scope.row}">编辑帖子</el-dropdown-item>
                <el-dropdown-item :command="{action: 'top', row: scope.row}">
                  {{ scope.row.isTop ? '取消置顶' : '设置置顶' }}
                </el-dropdown-item>
                <el-dropdown-item :command="{action: 'essence', row: scope.row}">
                  {{ scope.row.isEssence ? '取消精华' : '设置精华' }}
                </el-dropdown-item>
                <el-dropdown-item :command="{action: 'recommend', row: scope.row}">
                  {{ scope.row.isRecommend ? '取消推荐' : '设置推荐' }}
                </el-dropdown-item>
                <el-dropdown-item :command="{action: 'violation', row: scope.row}" divided>标记违规</el-dropdown-item>
                <el-dropdown-item :command="{action: 'delete', row: scope.row}" style="color: #F56C6C;">删除帖子</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryForm.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
    
    <!-- 帖子详情弹窗 -->
    <el-dialog title="帖子详情" :visible.sync="detailDialogVisible" width="800px">
      <div v-if="postDetail">
        <h3>{{ postDetail.title }}</h3>
        <p><strong>发布者:</strong> {{ postDetail.authorName }} ({{ getAuthorTypeText(postDetail.authorType) }})</p>
        <p><strong>分类:</strong> {{ postDetail.categoryName }}</p>
        <p><strong>状态:</strong> {{ getPostStatusText(postDetail.postStatus) }} / {{ getAuditStatusText(postDetail.auditStatus) }}</p>
        <p><strong>创建时间:</strong> {{ formatDateTime(postDetail.createTime) }}</p>
        <div style="margin-top: 20px;">
          <strong>内容:</strong>
          <div v-html="postDetail.content" style="margin-top: 10px; padding: 10px; border: 1px solid #ddd; border-radius: 4px;"></div>
        </div>
      </div>
    </el-dialog>
    
    <!-- 审核弹窗 -->
    <el-dialog title="审核帖子" :visible.sync="auditDialogVisible" width="500px">
      <el-form :model="auditForm" label-width="100px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio :label="1">审核通过</el-radio>
            <el-radio :label="2">审核拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="审核意见">
          <el-input 
            v-model="auditForm.auditRemark" 
            type="textarea" 
            :rows="4"
            placeholder="请输入审核意见">
          </el-input>
        </el-form-item>
      </el-form>
      
      <div slot="footer">
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit" :loading="auditLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getPostList, 
  getPostDetail, 
  auditPost,
  batchAuditPosts,
  publishPost,
  takeDownPost,
  setPostTop,
  setPostEssence,
  setPostRecommend,
  markPostViolation,
  deletePost,
  getCommunityStatistics 
} from '@/api/community'

export default {
  name: 'PostManagement',
  data() {
    return {
      loading: false,
      postList: [],
      total: 0,
      selectedPosts: [],
      statistics: {},
      
      queryForm: {
        keyword: '',
        authorName: '',
        postStatus: null,
        auditStatus: null,
        pageNum: 1,
        pageSize: 20
      },
      
      detailDialogVisible: false,
      postDetail: null,
      
      auditDialogVisible: false,
      auditLoading: false,
      auditForm: {
        id: null,
        auditStatus: 1,
        auditRemark: ''
      }
    }
  },
  
  created() {
    this.loadPostList()
    this.loadStatistics()
  },
  
  methods: {
    async loadPostList() {
      this.loading = true
      try {
        const response = await getPostList(this.queryForm)
        if (response.code === 200) {
          this.postList = response.data.list
          this.total = response.data.total
        }
      } catch (error) {
        this.$message.error('加载帖子列表失败')
      } finally {
        this.loading = false
      }
    },
    
    async loadStatistics() {
      try {
        const response = await getCommunityStatistics()
        if (response.code === 200) {
          this.statistics = response.data
        }
      } catch (error) {
        console.error('加载统计数据失败', error)
      }
    },
    
    handleSearch() {
      this.queryForm.pageNum = 1
      this.loadPostList()
    },
    
    handleReset() {
      this.queryForm = {
        keyword: '',
        authorName: '',
        postStatus: null,
        auditStatus: null,
        pageNum: 1,
        pageSize: 20
      }
      this.loadPostList()
    },
    
    handleRefresh() {
      this.loadPostList()
      this.loadStatistics()
    },
    
    handleSizeChange(val) {
      this.queryForm.pageSize = val
      this.queryForm.pageNum = 1
      this.loadPostList()
    },
    
    handleCurrentChange(val) {
      this.queryForm.pageNum = val
      this.loadPostList()
    },
    
    handleSelectionChange(selection) {
      this.selectedPosts = selection
    },
    
    async viewPostDetail(row) {
      try {
        const response = await getPostDetail(row.id)
        if (response.code === 200) {
          this.postDetail = response.data
          this.detailDialogVisible = true
        }
      } catch (error) {
        this.$message.error('获取帖子详情失败')
      }
    },
    
    auditPost(row, status) {
      this.auditForm = {
        id: row.id,
        auditStatus: status,
        auditRemark: ''
      }
      this.auditDialogVisible = true
    },
    
    async submitAudit() {
      this.auditLoading = true
      try {
        const response = await auditPost(
          this.auditForm.id,
          this.auditForm.auditStatus,
          this.auditForm.auditRemark
        )
        
        if (response.code === 200) {
          this.$message.success('审核成功')
          this.auditDialogVisible = false
          this.loadPostList()
        }
      } catch (error) {
        this.$message.error('审核失败')
      } finally {
        this.auditLoading = false
      }
    },
    
    async batchAudit(status) {
      if (this.selectedPosts.length === 0) {
        this.$message.warning('请选择要审核的帖子')
        return
      }
      
      const statusText = status === 1 ? '通过' : '拒绝'
      
      try {
        await this.$confirm(`确认批量${statusText}选中的帖子？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const postIds = this.selectedPosts.map(post => post.id)
        const response = await batchAuditPosts(postIds, status, `批量${statusText}`)
        
        if (response.code === 200) {
          this.$message.success(`批量${statusText}成功`)
          this.loadPostList()
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(`批量${statusText}失败`)
        }
      }
    },
    
    async batchPublish() {
      // TODO: 实现批量发布
      this.$message.info('批量发布功能开发中')
    },
    
    async batchTakeDown() {
      // TODO: 实现批量下架
      this.$message.info('批量下架功能开发中')
    },
    
    async takeDownPost(row) {
      try {
        const { value } = await this.$prompt('请输入下架原因', '下架帖子', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: value => value && value.trim().length > 0,
          inputErrorMessage: '请输入下架原因'
        })
        
        const response = await takeDownPost(row.id, value)
        if (response.code === 200) {
          this.$message.success('下架成功')
          this.loadPostList()
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('下架失败')
        }
      }
    },
    
    handleCommand(command) {
      const { action, row } = command
      
      switch (action) {
        case 'view':
          this.viewPostDetail(row)
          break
        case 'edit':
          this.$message.info('编辑功能开发中')
          break
        case 'top':
          this.toggleTop(row)
          break
        case 'essence':
          this.toggleEssence(row)
          break
        case 'recommend':
          this.toggleRecommend(row)
          break
        case 'violation':
          this.markViolation(row)
          break
        case 'delete':
          this.deletePost(row)
          break
      }
    },
    
    async toggleTop(row) {
      try {
        const response = await setPostTop(row.id, !row.isTop)
        if (response.code === 200) {
          this.$message.success(row.isTop ? '取消置顶成功' : '设置置顶成功')
          this.loadPostList()
        }
      } catch (error) {
        this.$message.error('操作失败')
      }
    },
    
    async toggleEssence(row) {
      try {
        const response = await setPostEssence(row.id, !row.isEssence)
        if (response.code === 200) {
          this.$message.success(row.isEssence ? '取消精华成功' : '设置精华成功')
          this.loadPostList()
        }
      } catch (error) {
        this.$message.error('操作失败')
      }
    },
    
    async toggleRecommend(row) {
      try {
        const response = await setPostRecommend(row.id, !row.isRecommend)
        if (response.code === 200) {
          this.$message.success(row.isRecommend ? '取消推荐成功' : '设置推荐成功')
          this.loadPostList()
        }
      } catch (error) {
        this.$message.error('操作失败')
      }
    },
    
    async markViolation(row) {
      this.$message.info('标记违规功能开发中')
    },
    
    async deletePost(row) {
      try {
        await this.$confirm('确认删除该帖子？删除后无法恢复！', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
        
        const response = await deletePost(row.id)
        if (response.code === 200) {
          this.$message.success('删除成功')
          this.loadPostList()
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },
    
    // 辅助方法
    formatDateTime(dateTime) {
      return dateTime ? new Date(dateTime).toLocaleString() : '-'
    },
    
    getContentSummary(content) {
      if (!content) return ''
      return content.length > 50 ? content.substring(0, 50) + '...' : content
    },
    
    getPostStatusText(status) {
      const texts = { 0: '草稿', 1: '待审核', 2: '已发布', 3: '已下架', 4: '已删除' }
      return texts[status] || '未知状态'
    },
    
    getPostStatusType(status) {
      const types = { 0: 'info', 1: 'warning', 2: 'success', 3: 'danger', 4: 'info' }
      return types[status] || ''
    },
    
    getAuditStatusText(status) {
      const texts = { 0: '待审核', 1: '审核通过', 2: '审核拒绝' }
      return texts[status] || '待审核'
    },
    
    getAuditStatusType(status) {
      const types = { 0: 'warning', 1: 'success', 2: 'danger' }
      return types[status] || ''
    },
    
    getAuthorTypeText(type) {
      const texts = { 'student': '学生', 'teacher': '教师', 'admin': '管理员' }
      return texts[type] || '学生'
    },
    
    getAuthorTypeColor(type) {
      const colors = { 'student': '', 'teacher': 'success', 'admin': 'warning' }
      return colors[type] || ''
    },
    
    getViolationTypeText(type) {
      const texts = { 
        'spam': '垃圾信息', 
        'inappropriate': '不当内容', 
        'copyright': '版权问题', 
        'other': '其他' 
      }
      return texts[type] || ''
    }
  }
}
</script>

<style lang="scss" scoped>
.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  
  .stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    
    i {
      font-size: 24px;
      color: white;
    }
  }
  
  .stat-content {
    flex: 1;
    
    .stat-title {
      font-size: 14px;
      color: #909399;
      margin-bottom: 8px;
    }
    
    .stat-value {
      font-size: 24px;
      font-weight: bold;
      color: #303133;
    }
  }
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  
  .toolbar-left {
    display: flex;
    gap: 8px;
  }
}
</style>